<template>
  <view class="canvas-container" :style="`height: ${this.height}px;width:${this.width}px`">
    <canvas canvas-id="circle-progress-bar__shadow" :style="`height: ${this.height}px;width:${this.width}px`"></canvas>
    <canvas canvas-id="circle-progress-bar__un-filled"
            :style="`height: ${this.height}px;width:${this.width}px`"></canvas>
    <canvas canvas-id="circle-progress-bar__filled" :style="`height: ${this.height}px;width:${this.width}px`"></canvas>
  </view>
</template>

<script>
import {createCanvasContext} from "@tarojs/taro"
import {min} from "../../utils"

export default {
  name: "circle-progress-bar",
  props: {
    width: {
      type: Number,
      default: 200,
    },
    height: {
      type: Number,
      default: 200,
    },
    unFilledCircleColor: {
      type: String,
      default: "#C4C1FF",
    },
    filledCircleColor: {
      type: String,
      default: "#6158ff",
    },
    lineWidth: {
      type: Number,
      default: 20,
    },
    percent: {
      type: Number,
      default: 20,
    }
  },
  data() {
    return {
      canvasUnfilled: null, //画布实例
      canvasFilled: null, //画布实例
      shadowCanvas: null, //画布实例
    }
  },
  methods: {
    drawArc(startAngle, endAngle, color, canvas, isShadowed) {
      console.log("startAngle",startAngle);
      console.log("endAngle",endAngle);
      console.log("color",color);
      canvas.restore();
      canvas.setFillStyle(color);
      canvas.clearRect(0, 0, this.width, this.height);
      canvas.draw(true); // 执行清除画布命令
      canvas.setLineWidth(this.lineWidth);
      canvas.setLineCap('round');
      canvas.beginPath();
      canvas.arc(
        this.width / 2,
        this.height / 2,
        min(this.width, this.height) / 2 - this.lineWidth - 5,// 5 是给 shadow 留的空间
        (startAngle - 0.5) * Math.PI,
        (endAngle - 0.5) * Math.PI,
        false
      );
      canvas.setStrokeStyle(color);
      isShadowed && canvas.setShadow(0, 5, 4, "#cccccc");
      canvas.stroke(); // 用 setStrokeStyle 设置的颜色开始画
      canvas.draw(true);
      canvas.save();
    }
  },
  created() {
    this.canvasUnfilled = createCanvasContext("circle-progress-bar__un-filled");
    this.canvasFilled = createCanvasContext("circle-progress-bar__filled");
    this.shadowCanvas = createCanvasContext("circle-progress-bar__shadow");
    this.drawArc(0, 2, this.unFilledCircleColor, this.canvasUnfilled);
    this.drawArc(0, 2 / 100 * this.percent, this.filledCircleColor, this.canvasFilled);
    this.drawArc(0.5, 1.5, "#cccccc", this.shadowCanvas, true);
  }
}
</script>

<style lang="less">
.canvas-container {
  position: relative;
}

canvas {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
</style>
